<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\common\controller;

use think\Controller;
use app\common\model\Sms as SmsM;

/**
 * 短信发送控制器
 * @package app\common\controller
 */
class Smscm extends Controller
{

    /*
     * 发送短信
     * phone 手机号码
     * content  短信内容
     * flag 短信类型 1：注册账号 2:找回密码 3：短信验证 4：短信提醒
     * code 验证码
     */
    public function sendsms($phone, $content, $flag, $code)
    {

//        $smsapi = "http://api.smsbao.com/";
//        $user = config('sms_user'); //短信平台帐号
//        $pass =config('sms_pass'); //短信平台密码
//        $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
//        $result =file_get_contents($sendurl);
        $result = '0';
        if ($result == '0') {
            //增加记录
            $codelog = array(
                'phone' => $phone,
                'code' => $code,
                'create_time' => time(),
                'status' => '1',
                'type' => $flag,
                'content' => $content
            );
            $res = SmsM::insert($codelog);
            if ($res) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /*
     * 验证短信验证码是否正确
     * code 验证码
     * phone 手机号码
     * type 短信类型
     */
    public function check_smscode($phone, $code, $type)
    {
        $smscode = SmsM::where('phone', $phone)->where('code', $code)->where('status', 1)
            ->where('type', $type)->order('id desc')->find();
        if ($smscode) {
            //验证码过期15分钟
            if ($smscode['create_time'] + 60 * 15 < time()) {
                $msg = ['code' => 204, 'msg' => '验证码已过期', 'data' => ''];
                return $msg;
            }
            SmsM::where('id', $smscode['id'])->update(['status' => 2]);
            $msg = ['code' => 200, 'msg' => '验证通过', 'data' => ''];
            return $msg;
        } else {
            $msg = ['code' => 204, 'msg' => '验证码错误', 'data' => ''];
            return $msg;
        }
    }

    //随机短信验证码
    public function sms_rand($length = 6)
    {
        $characters = '0123456789';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}